/*
 * Alexey Danchuk
 * This software is an implementation of the task from OOP module.
 */
package parser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import input.InputFromFile;
import static parser.Parser.QUESTION_REPRESENTATION;

/**
 * This class describes basics issues about question input from file parser.
 *
 * @version 2.03 20 February 2013
 * @author Alexey Danchuk
 */
public class FileParser extends Parser {

    private String[][] fileRepresentation = null;
    public InputFromFile input = new InputFromFile();

    private String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }

    private void fillFileRepresentation(String filename) throws IOException {
        String[] lines = readLines(filename);
        int rows = lines.length / QUESTION_REPRESENTATION;
        int columns = QUESTION_REPRESENTATION;
        if ((lines.length % QUESTION_REPRESENTATION) == 0) {
            fileRepresentation = new String[rows][columns];
            for (int index = 0; index < lines.length; index++) {
                int column = index % columns;
                int row = (index - column) / columns;
                fileRepresentation[row][column] = lines[index];
            }
        } else {
            System.err.println("Error with your file.");
        }
    }

    @Override
    public void parse(String filename) throws IOException {
        fillFileRepresentation(filename);
    }

    /**
     * @return the fileRepresentation
     */
    public String[][] getFileRepresentation() {
        return fileRepresentation;
    }
}
